<style lang="less" scoped>
.yzmbox {
  position: absolute;
  top: -79px;
  z-index: 99;
  left: 28px;
  background: #eee;
  box-shadow: 1px 0px 13px 2px #b5b5b5;
  border-radius: 5px;
  height: 80px;
  overflow: hidden;
  display: block;
}
</style>

<template>
  <Modal v-draggable="options"
         v-model="modal"
         title="欢迎登录"
         width="300"
         :mask-closable="false">
    <Form ref="loginForm"
          :model="form"
          :rules="rules"
          @keydown.enter.native="handleSubmit">
      <FormItem prop="userName">
        <Input @on-focus="yzmfocus()"
               @on-blur="yzqx"
               v-model="form.userName"
               placeholder="请输入用户名">
        <span slot="prepend">
          <Icon :size="16"
                type="ios-person"></Icon>
        </span>
        </Input>
      </FormItem>
      <FormItem prop="password">
        <Input @on-focus="yzmfocus()"
               type="password"
               v-model="form.password"
               placeholder="请输入密码">
        <span slot="prepend">
          <Icon :size="14"
                type="md-lock"></Icon>
        </span>
        </Input>
      </FormItem>
      <FormItem prop="captchaCode"
                class="v-ivu-append">
        <Input ref="yzmInput"
               @on-focus="focus();yzmfocus()"
               @on-blur="blur"
               size="large"
               type="text"
               v-model="form.captchaCode"
               placeholder="请输入验证码">
        <span slot="prepend">
          <Icon :size="14"
                type="md-umbrella" />
        </span>
        <Button slot="append"
                icon="md-refresh"
                @click="renovateCode"></Button>
        </Input>
        <div class="yzmbox"
             v-if="y">
          <a style="display:  block;"
             @click="getyzm"><img :src="this.Img"></a>
        </div>
      </FormItem>
      <Alert v-if="aerr"
             style="margin-top: 10px;margin: 0 auto;"
             type="error"
             show-icon>{{errText}}</Alert>
    </Form>
    <div slot="footer">
      <Button @click="handleSubmit"
              type="primary"
              long>登录</Button>
    </div>
  </Modal>
</template>
<script>
export default {
  name: 'LoginForm',
  props: {
    userNameRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '账号不能为空', trigger: 'blur' }
        ]
      }
    },
    passwordRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ]
      }
    },
    captchaCodeRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ]
      }
    },
    modalRegister: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      aerr: false,
      errText: '',
      adminName: '',
      role_id: 1,
      y: false,
      Img: '',
      modal: false,
      options: {
        trigger: '.ivu-modal-header',
        body: '.ivu-modal',
        recover: true
      },
      form: {
        userName: '',
        password: '',
        captchaCode: '',
        CapKey: {
          key: ''
        }
      }
    }
  },
  watch: {
    modalRegister (value) {
      if (value === true) {
        this.yzmfocus()
        this.$refs.loginForm.resetFields()
        this.form.CapKey.key = ''
        this.getyzm()
      }
      this.modal = value
    },
    modal (value) {
      this.$emit('on-modal-valid', value)
    }
  },
  computed: {
    rules () {
      return {
        userName: this.userNameRules,
        password: this.passwordRules,
        captchaCode: this.captchaCodeRules
      }
    }
  },
  mounted () {

  },
  methods: {
    handleSubmit () {
      let _this = this
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$api.login({ name: this.role_id === 3 ? this.adminName : this.form.userName, password: this.form.password, captcha: this.form.captchaCode, cap_key: this.form.CapKey.key, role_id: this.role_id }).then(response => {
            response.json().then(res => {
              if (res.code === 2) {
                _this.aerr = true
                _this.errText = res.msg
                _this.form.captchaCode = ''
                _this.getyzm()
              } else if (res.code === 1) {
                _this.modal = false
                this.$emit('on-success-valid', res)
              }
            })
          })
        }
      })
    },
    yzqx () {
      let arr = this.form.userName.split(':')
      if (arr.length === 2 && arr[0] === 'm' && arr[1] !== '') {
        this.role_id = 3
        this.adminName = arr[1]
      } else {
        this.role_id = 1
      }
    },
    focus () {
      this.y = true
    },
    yzmfocus () {
      this.aerr = false
      this.errText = ''
    },
    blur () {
      this.y = false
    },
    renovateCode () {
      this.getyzm()
      this.$refs.yzmInput.focus()
    },
    getyzm () {
      let _this = this
      if (this.form.CapKey.key === '') {
        this.$api.getCaptcha().then(function (response) {
          _this.form.CapKey.key = response.headers.get('Set-Cap-Key')
          response.blob().then(function (responseBlob) {
            if (_this.Img) window.URL.revokeObjectURL(_this.Img)
            _this.Img = window.URL.createObjectURL(responseBlob)
          })
        })
      } else {
        this.$api.getCaptcha(this.form.CapKey).then(function (response) {
          response.blob().then(function (responseBlob) {
            if (_this.Img) {
              window.URL.revokeObjectURL(_this.Img)
            }
            _this.Img = window.URL.createObjectURL(responseBlob)
          })
        })
      }
    }
  }
}
</script>
